package com.lxl.workbench.controller;

import com.alibaba.fastjson.JSON;
import com.lxl.commons.contants.BaseServlet;
import com.lxl.commons.contants.Contants;
import com.lxl.commons.domain.ReturnObject;
import com.lxl.commons.utils.UUIDUtils;
import com.lxl.workbench.entity.Book;
import com.lxl.workbench.entity.Category;
import com.lxl.workbench.service.BookService;
import com.lxl.workbench.service.CategoryService;
import com.lxl.workbench.service.impl.BookServiceImpl;
import com.lxl.workbench.service.impl.CategoryServiceImpl;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 北上寻海
 */
@WebServlet({"/queryBook","/borrowBook","/lendBook","/deleteBook","/addBook","/selectBook","/updateBook"})
public class BookServlet extends BaseServlet {
    /**
     *注入BookService对象
     */
    BookService bookService = new BookServiceImpl();
    CategoryService categoryService = new CategoryServiceImpl();

    /**
     * 返回前端页面信息的对象
     */
    ReturnObject returnObject = new ReturnObject();

    /**
     * 查询书籍
     * @param request 会话域
     * @param response 响应域
     * @throws IOException io异常
     */
    public void   queryBookByCondition(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取查询条件
        String bookName = request.getParameter("bookName");
        String bookType = request.getParameter("bookType");
        String bookAuthor = request.getParameter("bookAuthor");
        List<Book> bookList;
        try {
            bookList = bookService.selectBookByCondition(bookName,bookType,bookAuthor);
            if(bookList!=null&&!bookList.isEmpty()){
                returnObject.setMessage("查询成功");
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setRetData(bookList);
            }else {
                returnObject.setMessage("无此类书籍");
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setRetData(null);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
        }

        //bean对象转化为json对象
        String json =  JSON.toJSONString(returnObject);
        //把json数据响应给后台
        response.getWriter().write(json);
    }

    /**
     * 借出书籍
     * @param request 会话域
     * @param response 响应域
     * @throws IOException io异常
     */
    public void borrowBookByIds (HttpServletRequest request, HttpServletResponse response) throws IOException {

        String idStr =  request.getParameter("ids");
        //前端拼接的的字符串带着 /
        String idStrReplace = idStr.replace("/","");
        String [] ids = idStrReplace.split(",");
        int number = Integer.parseInt(request.getParameter("number"));
        try {
            //先把它们都查出来，判断一下数量是否足够调度
            List<Book> books = bookService.selectBookByIds(ids);
            //存放运算后的remaining
            int []  remainingArray = new int[books.size()];
            for(int i = 0;i<books.size();i++){
                Book book = books.get(i);
                if(book.getRemaining()<number){
                    returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                    returnObject.setMessage("剩余书籍数量不足");
                } else {
                    remainingArray[i] = books.get(i).getRemaining()-number;
                    try {
                        int result = bookService.updateBookByIds(ids,remainingArray);
                         if(result>0) {
                             returnObject.setMessage("成功借出");
                             returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                         }else {
                             returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
                             returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                         }
                    } catch (SQLException e) {
                        e.printStackTrace();
                        returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
                        returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //bean对象转化为json对象
        String json =  JSON.toJSONString(returnObject);
        //把json数据响应给后台
        response.getWriter().write(json);
    }

    /**
     * 借入书籍
     * @param request 会话域
     * @param response 响应域
     * @throws IOException io异常
     */
    public void lendBookByIds (HttpServletRequest request, HttpServletResponse response) throws IOException {

        String idStr =  request.getParameter("ids");
        //前端拼接的的字符串带着 /
        String idStrReplace = idStr.replace("/","");
        String [] ids = idStrReplace.split(",");

        int number = Integer.parseInt(request.getParameter("number"));
        //存储返回数据的对象

        try {
            //先把它们都查出来，加上调度数量在传回去
            List<Book> books = bookService.selectBookByIds(ids);
            //存放运算后的remaining
            int []  remainingArray = new int[books.size()];
            for(int i = 0;i<books.size();i++){
                Book book = books.get(i);
                remainingArray[i] = books.get(i).getRemaining()+number;
                try {
                    int result = bookService.updateBookByIds(ids,remainingArray);
                    if(result>0) {
                        returnObject.setMessage("成功借入");
                        returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                    }else {
                        returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
                        returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                    returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
                    returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        //bean对象转化为json对象
        String json =  JSON.toJSONString(returnObject);
        //把json数据响应给后台
        response.getWriter().write(json);
    }

    /**
     * 书目管理员删除他类型下的书
     * @param request 请求域
     * @param response 响应域
     * @throws IOException IO异常
     */
    public void deleteBookByIds (HttpServletRequest request, HttpServletResponse response) throws IOException {
        String idStr =  request.getParameter("ids");
        //前端拼接的的字符串带着 /
        String idStrReplace = idStr.replace("/","");
        String [] delIds = idStrReplace.split(",");
        try {
            int result = bookService.deleteBookByIds(delIds);
            if(result>0){
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setMessage("删除成功");
            }else {
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("删除失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
        }
        //bean对象转化为json对象
        String json =  JSON.toJSONString(returnObject);
        //把json数据响应给后台
        response.getWriter().write(json);
    }


    /**
     * 添加书籍，添加着是该书目的管理员
     * @param request 请求域
     * @param response 响应域
     * @throws IOException io异常
     */
    public void addBookByCondition (HttpServletRequest request, HttpServletResponse response) throws IOException {
        String manageType = request.getParameter("bookType");
        String bookType = null;
        try {
             List<Category> categoryList = categoryService.selectCategoryId(manageType);
             if(categoryList!=null&&!categoryList.isEmpty()){
                 bookType = categoryList.get(0).getId();
             }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        Book book = new Book(UUIDUtils.getUuid(),
                request.getParameter("isbn"),
                request.getParameter("bookName"),
                bookType,
                Integer.parseInt(request.getParameter("remaining")),
                request.getParameter("price"),
                request.getParameter("author"));
        try {
            int result = bookService.insertBook(book);
            if(result>0){
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setMessage("添加成功");
                returnObject.setRetData(book);
            }else {
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("添加失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
        }
        //bean对象转化为json对象
        String json =  JSON.toJSONString(returnObject);
        //把json数据响应给后台
        response.getWriter().write(json);

    }


    /**
     * 通过id查book的信息，因为更新之前要把数据先查出来先
     * @param request 请求域
     * @param response 响应域
     * @throws IOException io异常
     */
    public void selectBookById (HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        String[] selId = {id.replace("/","")};
        try {
            List<Book> bookList = bookService.selectBookByIds(selId);
            if(bookList!=null&&!bookList.isEmpty()){

                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setMessage("查询成功");
                returnObject.setRetData(bookList.get(0));
            }else {
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("查询失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
        }
        //bean对象转化为json对象
        String json =  JSON.toJSONString(returnObject);
        //把json数据响应给后台
        response.getWriter().write(json);
    }

    /**
     * 根据前端发来的数据，封装成book，更新数据
     * @param request 请求域
     * @param response 响应域
     * @throws IOException io异常
     */
    public void updateBookByCondition (HttpServletRequest request, HttpServletResponse response) throws IOException {

        Book book = new Book();
        book.setId(request.getParameter("id"));
        book.setIsbn(request.getParameter("isbn"));
        book.setBookName(request.getParameter("bookName"));
        book.setRemaining( Integer.parseInt(request.getParameter("remaining")));
        book.setPrice(request.getParameter("price"));
        book.setAuthor(request.getParameter("author"));

        try {
            int result = bookService.updateBookByCondition(book);
            if(result>0){
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setMessage("更新成功");
            }else {
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("更新失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage(Contants.RETURN_OBJECT_MESSAGE_FAIL);
        }
        //bean对象转化为json对象
        String json =  JSON.toJSONString(returnObject);
        //把json数据响应给后台
        response.getWriter().write(json);
    }

}
